package com.example.review;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class chapterSix3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chapter_six3);
        Button button=findViewById(R.id.sh_save);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getSharedPreferences方式获取sharedPreferences对象
                //两个参数分别为文件的名字，操作模式MODE_PRIVATE表示只有当前的应用 程序才可以对这个SharedPreferences文件进行读写
                SharedPreferences sharedPreferences = getSharedPreferences("person", MODE_PRIVATE);
                //获取一 个SharedPreferences.Editor 对象。
                SharedPreferences.Editor editor = sharedPreferences.edit();
                //添加数据
                editor.putString("name","张三");
                editor.putInt("age",18);
                editor.putBoolean("nan",true);
                //将添加的数据提交，从而完成数据存储操作
                editor.apply();
            }
        });


        Button button1=findViewById(R.id.sh_read);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences=getSharedPreferences("person",MODE_PRIVATE);
                String name=sharedPreferences.getString("name","默认值");
                int age=sharedPreferences.getInt("age",0);
                Boolean nan=sharedPreferences.getBoolean("nan",true);
                Toast.makeText(chapterSix3Activity.this, "name: "+name+"age: "+"男？ "+nan, Toast.LENGTH_SHORT).show();
            }
        });
    }
}